﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Fitts__law_experiment_with_a_wiimote
{
    public partial class ExperimentViewer : Form
    {
        public ExperimentViewer()
        {
            InitializeComponent();
        }

        private void BBrowse_Click(object sender, EventArgs e)
        {
            if (GetExperimentFile.ShowDialog() != DialogResult.OK)
                return;
            TbFile.Text = GetExperimentFile.FileName;
        }

        private void BClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void BLoad_Click(object sender, EventArgs e)
        {
			LbEvents.Items.Clear();
            String file = TbFile.Text;
            String filename = Path.GetFileName(file);
            Experiment exp;
            try
            {
               exp = Experiment.LoadFromFile(file);
            }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); return; }
            Gb.Text = "Experiment | " + filename + " | " + exp.Name;
            LEventCount.Text = "Events: " + exp.Events.Count;
            int clickCount = 0;
            int moveCount = 0;
            foreach (Experiment.ExperimentEvent ev in exp.Events)
            {
                if (ev is Experiment.ExperimentMouseUpEvent)
                {
                    clickCount++;
                }
                else if (!(ev is Experiment.ExperimentMouseUpEvent))
                {
                    moveCount++;
                }
                LbEvents.Items.Add(ev.ToString());
            }
            LClickCount.Text = "Clicks: " + clickCount;
        }

		private void BBatchExport_Click(object sender, EventArgs e)
		{
			if (getFolder.ShowDialog() != DialogResult.OK)
				return;
			String sourceDir = getFolder.SelectedPath;
			if (getFolder.ShowDialog() != DialogResult.OK)
				return;
			String targetDir = getFolder.SelectedPath;

			String[] files = System.IO.Directory.GetFiles(sourceDir , "*.exd", SearchOption.AllDirectories);
            String filename = Path.GetFileNameWithoutExtension(files[0]);
            String path = targetDir + "\\" + filename;

            //export
            StreamWriter writer = null;
            try
            {
                writer = new System.IO.StreamWriter(path);
                writer.WriteLine("Time	Width	Distance	D/W	ID");
                foreach (String file in files)
                {
                    writeExperiment(Experiment.LoadFromFile(file), writer, Math.Max(0, cbType.SelectedIndex));
                    writer.WriteLine();
                }
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }
		}

		public void exportExperiment(Experiment exp, String path, int type)
		{
			if (exp == null)
				throw new ArgumentException("Exp is null");
			String dir = System.IO.Directory.GetParent(path).FullName;
			if (!System.IO.Directory.Exists(dir))
			{
				try
				{
					System.IO.Directory.CreateDirectory(dir);
				}
				catch (Exception ex)
				{ MessageBox.Show(ex.Message); }
			}

			//export
			StreamWriter writer = null;
			try
			{
				writer = new System.IO.StreamWriter(path);
				writer.WriteLine("Time	Width	Distance	D/W ID");
                writeExperiment(exp, writer, Math.Max(0, cbType.SelectedIndex));
			}
			finally
			{
				if (writer != null)
					writer.Close();
			}
		}

        public void writeExperiment(Experiment exp, StreamWriter writer, int type)
        {
            try
            {
                long beginT = 0;
                long T = 0;
                double W = 0;
                double D = 0;
                Point beginMousePos = new Point(-1, -1);
                Experiment.ExperimentEvent ev = exp.Events[0];
                Experiment.ExperimentEvent previousEvent = null;

                //search for the start event
                int target = 0;
                int ind = 0;
                while (target != 2)
                {
                    ev = exp.Events[ind];
                    target = exp.Events[ind + 1].target;
                    ind += 1;
                }
                beginT = ev.timestamp;
                beginMousePos.X = ev.mouseX;
                beginMousePos.Y = ev.mouseY;
                previousEvent = ev;
                for (int i = ind; i < exp.Events.Count - 1; i++)
                {
                    ev = exp.Events[i];
                    if ((previousEvent.target != ev.target) && (i > ind))
                    {
                        //our target switched, the previous event must have been a mouseUp
                        T = (previousEvent.timestamp - beginT) / TimeSpan.TicksPerMillisecond;
                        if (type == 0)
                            W = previousEvent.rect.Width;
                        else if (type == 1)
                            W = previousEvent.rect.Height;
                        else
                            W = Math.Min(previousEvent.rect.Width, previousEvent.rect.Height);
                        D = Math.Sqrt(Math.Pow(Math.Abs(beginMousePos.X - (previousEvent.rect.X + previousEvent.rect.Width / 2)), 2) +
                            Math.Pow(Math.Abs(beginMousePos.Y - (previousEvent.rect.Y + previousEvent.rect.Height / 2)), 2));
                        writer.WriteLine("" + T + "	" + W + "	" + D + "	" + D / W + "	" + Math.Log(D / W + 1, 2));
                        beginT = previousEvent.timestamp;
                        beginMousePos.X = previousEvent.mouseX;
                        beginMousePos.Y = previousEvent.mouseY;
                    }
                    previousEvent = ev;
                }
                //handle last switch
                ev = exp.Events[exp.Events.Count - 1];
                T = (ev.timestamp - beginT) / TimeSpan.TicksPerMillisecond;
                W = ev.rect.Width;
                D = (int)Math.Sqrt(Math.Pow(Math.Abs(beginMousePos.X - (ev.rect.X + ev.rect.Width / 2)), 2) +
                    Math.Pow(Math.Abs(beginMousePos.Y - (ev.rect.Y + ev.rect.Height / 2)), 2));
                writer.WriteLine("" + T + "	" + W + "	" + D + "	" + D / W + "	" + Math.Log(D / W + 1, 2));
            }
            catch (Exception e)
            { }
        }

		private void BExport_Click(object sender, EventArgs e)
		{
			if (getFolder.ShowDialog() != DialogResult.OK)
				return;
			String targetDir = getFolder.SelectedPath;
			String file = TbFile.Text;
			String filename = Path.GetFileNameWithoutExtension(file);
			exportExperiment(Experiment.LoadFromFile(file), targetDir + "\\" + filename + ".txt", Math.Max(0, cbType.SelectedIndex));
		}

        private void ExperimentViewer_Load(object sender, EventArgs e)
        {

        }
    }
}
